//
//  OECommitViewController.m
//  OneEightyNine
//
//  Created by Mac on 2019/3/8.
//  Copyright © 2019 stoneobs. All rights reserved.
//

#import "OECommitViewController.h"
#import "OECommitOrderTableViewCell.h"
#import "OECommitOrderSuccessViewController.h"
@interface OECommitViewController ()<BMKMapViewDelegate>
@property(nonatomic, strong) BMKMapView                        *mapView;
@property(nonatomic, strong) STButton                     *timeButton;/**<  */
@property(nonatomic, assign) BOOL                     isShowed;/**< <##> */
@end

@implementation OECommitViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = OESTRING(@"PLACE ORDER");
    [self configSubView];
    [self configTableFooterView];
    // Do any additional setup after loading the view.
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (self.isShowed) {
        [self st_showAlertTitle:@"Order  time out ,please make order agin" message:@"" andWithBlock:^(NSString *name) {
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }
    self.isShowed = YES;
}
#pragma mark --subView
- (void)configSubView{
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    
    _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 0 , UIScreenWidth, UIScreenHeight * 0.3)];
    _mapView.delegate = self;
    CLLocationCoordinate2D center =  CLLocationCoordinate2DMake(STLocationManger.defult.ipy.floatValue,
                                                                STLocationManger.defult.ipx.floatValue);
    BMKCoordinateSpan span =  BMKCoordinateSpanMake(5, 5);
    BMKCoordinateRegion regin = BMKCoordinateRegionMake(center, span);
    _mapView.region = regin;
    _mapView.gesturesEnabled = YES;
    _mapView.zoomLevel = 18;
    [_mapView setCenterCoordinate:center animated:YES];
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = BMKUserTrackingModeHeading;
    [header addSubview:_mapView];
    
    NSString * time = [NSString stringWithFormat:@"%@-%@",self.model.start_time,self.model.end_time];
    
    self.timeButton = [[STButton alloc] initWithFrame:CGRectMake(15, _mapView.bottom, UIScreenWidth - 15, 44)
                                                     title:[NSString stringWithFormat:@"Pick up time  (%@)",time]
                                                titleColor:FirstTextColor
                                                 titleFont:15
                                              cornerRadius:0
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:nil];
    [self.timeButton setAttributedTitle:[self.timeButton.currentTitle st_convertAttributeStringWithKeyWord:time attributes:@{NSForegroundColorAttributeName:OE_LIMITE_COLOR}] forState:UIControlStateNormal];
    [header addSubview:self.timeButton];
    
    UIImageView * imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"12×20店铺箭头"]];
    imageView.centerY = self.timeButton.height / 2;
    imageView.right = self.timeButton.width - 10;
    [self.timeButton addSubview:imageView];
    
    UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, self.timeButton.bottom, UIScreenWidth, 10)];
    line.backgroundColor = OE_GrayColor;
    [header addSubview:line];

    STButton * iconButton = [[STButton alloc] initWithFrame:CGRectMake(15, line.bottom + 10, 34, 34)
                                                     title:nil
                                                titleColor:nil
                                                 titleFont:0
                                              cornerRadius:17
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:nil];
    [iconButton sd_setBackgroundImageWithURL:[NSURL URLWithString:self.model.supplier_logo] forState:UIControlStateNormal];
    [header addSubview:iconButton];
    
    STButton * titleButton = [[STButton alloc] initWithFrame:CGRectMake(iconButton.right  +5, 0, 200, 34)
                                                     title:self.model.supplier_name
                                                titleColor:FirstTextColor
                                                 titleFont:14
                                              cornerRadius:0
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:nil];
    [header addSubview:titleButton];
    titleButton.centerY = iconButton.centerY;
    header.height = titleButton.bottom + 10;
    
    self.tableView.tableHeaderView = header;
    
}
- (void)configTableFooterView{
//    __weak typeof(self) weakSelf =  self;
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 80)];
    footer.backgroundColor = self.tableView.backgroundColor;
    NSString * money = [self allPrice];
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 44)
                                                     text:[NSString stringWithFormat:@"A total of %ld pieces payment$%@",self.dataSouce.count,money]
                                                textColor:FirstTextColor
                                                     font:14
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentRight];
    titleLable.right = UIScreenWidth - 15;
    NSString * redStinrg = [NSString stringWithFormat:@"$%@",money];
    titleLable.attributedText = [titleLable.text st_convertAttributeStringWithKeyWord:redStinrg attributes:@{NSForegroundColorAttributeName:FlatRed}];
    [footer addSubview:titleLable];
    self.tableView.tableFooterView = footer;
    
    UIView * bootomView = [[UIView alloc] initWithFrame:CGRectMake(0, TMUtils.tabBarTop, UIScreenWidth, 49)];
    bootomView.backgroundColor = UIColor.whiteColor;
    [bootomView st_showTopLine];
    bootomView.userInteractionEnabled = YES;
    [self.view addSubview:bootomView];
    
    STLabel * stitleLable = [[STLabel alloc] initWithFrame:CGRectMake(15, 0, UIScreenWidth, 44)
                                                     text:[NSString stringWithFormat:@"payment$%@",money]
                                                textColor:FirstTextColor
                                                     font:13
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    stitleLable.attributedText = [stitleLable.text st_convertAttributeStringWithKeyWord:redStinrg attributes:@{NSForegroundColorAttributeName:FlatRed}];
    [bootomView addSubview:stitleLable];
    __weak typeof(self) weakSelf =  self;
    STButton * downbutton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 0.35 *UIScreenWidth, 49)
                                                      title:@"Place Order"
                                                 titleColor:UIColor.whiteColor
                                                  titleFont:18
                                               cornerRadius:0
                                            backgroundColor:OE_LIMITE_COLOR
                                            backgroundImage:nil
                                                      image:nil];
    downbutton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [bootomView addSubview:downbutton];
    [downbutton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedConfimButton];
    }];
    downbutton.right = UIScreenWidth;
    
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.frame = CGRectMake(0, TMUtils.navgationBarBootom, UIScreenWidth, TMUtils.tabBarTop - TMUtils.navgationBarBootom);
}
- (NSString*)allPrice{
    CGFloat money = 0;
    NSInteger num = 0;
    for (OEGoodModel * goodModel in self.dataSouce) {

            num ++ ;
            NSString * realDanPrice = [goodModel.goods_price stringByReplacingOccurrencesOfString:@"￥" withString:@""];
            money = realDanPrice.floatValue *  goodModel.subtotal_number.integerValue + money;
    }
    return [NSString stringWithFormat:@"%0.2f",money];
}

#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return OECommitOrderTableViewCell.cellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    OECommitOrderTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[OECommitOrderTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    OEGoodModel * model = self.dataSouce[indexPath.row];
    cell.model = model;
    return cell;
}
#pragma mark --Action Method
- (void)onSelctedConfimButton{
    if (!self.dataSouce.count) {
        return;
    }

    BOOL isOpenFaceOrFinger = [[NSUserDefaults standardUserDefaults] boolForKey:OE_FACE_OR_FINGER_PAY_OPEN_KEY];
    if (isOpenFaceOrFinger) {
        [TMUtils showFaceOrFingerPayType:@"2" handle:^{

           [self sendMakeOrderQerequest];
        } inputPwdHandle:^{
            OEPwdInPutViewController * vc = OEPwdInPutViewController.new;
            vc.pwd = STUserManger.defult.loginedUser.pay_password;
            [vc setOnInputTruePwd:^{
               [self sendMakeOrderQerequest];
            }];
            [self presentViewController:vc animated:NO completion:nil];
            
        } errorHandle:^{
            
        }];
    }else{
        OEPwdInPutViewController * vc = OEPwdInPutViewController.new;
        vc.pwd = STUserManger.defult.loginedUser.pay_password;
        [vc setOnInputTruePwd:^{
            [self sendMakeOrderQerequest];
        }];
        [self presentViewController:vc animated:NO completion:nil];
    }
    
    

}
- (void)sendMakeOrderQerequest{
    NSArray * array = [self.dataSouce st_arrayFromObjKeyName:@"obj.rec_id"];
    NSString * recids = [array componentsJoinedByString:@","];
    [OEHomeDataController sendCommitOrderRequestWithRec_ids:recids supplier_id:self.model.supplier_id handle:^(BOOL success, NSString *errorString, NSDictionary *resp) {
        if (success) {
            OECommitOrderSuccessViewController * vc = OECommitOrderSuccessViewController.new;
            vc.time = [NSString stringWithFormat:@"%@-%@",self.model.start_time,self.model.end_time];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [SVProgressHUD showErrorWithStatus:@"Make Order error"];
        }
    }];
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

@end
